package com.xy.netty.dome.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteOrder;

/**
 * @author 1
 */
@Slf4j
public class EchoClientLengthFieldBasedHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        log.info("Client received：{}",msg.toString(CharsetUtil.UTF_8));
    }

    /**
     * 发送 案列1 消息
     * @param ctx
     * @param msg
     * @throws Exception
     */
    private void sendOneMsg(ChannelHandlerContext ctx,String msg) throws Exception {
        byte[] data = msg.getBytes(CharsetUtil.UTF_8);
        int bodyLen = data.length;
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
        //写入长度
        buf.writeShort(bodyLen);
        //写入输入内容
        buf.writeBytes(data);
        ctx.channel().writeAndFlush(buf);
    }
    /*例子5*/
    private void sendOneMsg4(ChannelHandlerContext ctx,String msg) throws Exception {
        final int header1 = 0xCAFE;
        byte[] data = msg.getBytes(CharsetUtil.UTF_8);
        int bodyLen = data.length;
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
        buf.writeMedium(bodyLen);
        buf.writeShort(header1);
        buf.writeBytes(data);
        ctx.channel().writeAndFlush(buf);
    }

    /*例子6*/
    private void sendOneMsg5(ChannelHandlerContext ctx,String msg) throws Exception {
        final int header1 = 0xCA;
        final int header2 = 0xFE;
        byte[] data = msg.getBytes(CharsetUtil.UTF_8);
        int bodyLen = data.length;
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();

        buf.writeByte(header1);
        buf.writeShort(bodyLen);
        buf.writeByte(header2);
        buf.writeBytes(data);
        // 整个包的消息长度
//        int msgLen = data.length + 1 + 1 + 2;
//        buf.writeByte(header1);
//        buf.writeShort(msgLen);
//        buf.writeByte(header2);
//        buf.writeBytes(data);
        ctx.channel().writeAndFlush(buf);
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("Active");
        String msg = null;
        for (int i = 1; i <= 10; i++) {
             msg = String.format("%s客户端发送信息测试：%s",System.lineSeparator(),i);
            sendOneMsg4(ctx,msg);
        }
        log.info("发送测试信息成功");
    }


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("EchoClientDelimiterHandler channelReadComplete");
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("exceptionCaught",cause);
        ctx.close();
    }
}
